import {
  OnInit,
  OnChanges,
  OnDestroy,
  Component,
  ChangeDetectionStrategy,
  ViewEncapsulation,
  Input,
  TemplateRef,
  NgZone,
  ViewChild,
  ElementRef,
} from '@angular/core';
import { InputNumber, InputBoolean } from 'ng-zorro-antd';
import { Lbchart } from '@shared';
import { Subscription } from 'rxjs';
import { SupData } from '@core/lb/SupData';
/**
 * 堆叠饼图
 */
@Component({
  selector: 'lb-stack-pie',
  template: `
    <div #stackpie></div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush, // 检测改为按需，即不自动刷新
})
export class LbStackPieComponent
  implements OnInit, OnChanges, OnDestroy, Lbchart {
  private chart: any;
  private resize$: Subscription;
  @ViewChild('stackpie', { static: true }) private node: ElementRef;
  @Input() padding: Array<number | string> | string = 'auto';
  @Input() @InputNumber() delay = 0;
  @Input() color: string[] = null;
  @Input() colorFiled = 'name';
  @Input() position: any;

  // @Input() style: { [key: string]: string };
  // @Input() position: { x: string, y: string, z: string } = { x: 'adc', y: 'sold', z: 'type' }

  @Input() data: any[];

  @Input() height: number;

  @Input() @InputBoolean() tooltipshow = true;
  @Input() @InputBoolean() tooltipshowpercent = true;
  @Input() @InputBoolean() tooltipshowtitle = false;

  @Input() legendposition;
  @Input() legendlayout;
  @Input() @InputBoolean() legendshow = true;
  @Input() @InputBoolean() legendshowpercent = true;

  @Input() @InputBoolean() labelshow = false;

  innerpie: any;
  outterpie: any;

  constructor(private ngZone: NgZone, private supdata: SupData) {}

  commonStyleHandle(chart, data) {
    const tpdata = data.map(ele => {
      return {
        [this.position.x]: ele[this.position.x],
        [this.position.z]: ele[this.position.x] + ele[this.position.z],
        [this.position.y]: ele[this.position.y]
      }
    })
    const dv = new DataSet.View().source(tpdata);
  
    console.log(this.position)
    console.log(dv.rows)
    // chart.source(dv.rows);
    dv.transform({
      type: 'percent',
      field: this.position.y,
      dimension: this.position.x,
      as: 'percent',
    });
    dv.transform({
      type: 'sort-by',
      fields: [ this.position.x, this.position.z ], // 根据指定的字段集进行排序，与lodash的sortBy行为一致
      order: 'ASC'        // 默认为 ASC，DESC 则为逆序
    })
    console.log('----报错了么啊')

    chart.source(dv, {
      percent: {
        formatter: val => {
          val = (val * 100).toFixed(2) + '%';
          return val;
        },
      },
    });
    chart.coord('theta', {
      radius: 0.5,
    });

    if(this.tooltipshow) {
      chart.tooltip({
        showTitle: this.tooltipshowtitle,
        itemTpl:
          '<li data-index={index}>' +
          '<span style="background-color:{color};width:8px;height:8px;border-radius:50%;display:inline-block;margin-right:8px;"></span>' +
          '{name}: {value}' + (this.tooltipshowpercent?' ({percent})':'')+
          '</li>',
      });
    } else {
      chart.tooltip(false)
    }
    
    // chart.legend(false);
       // 图例
       if (this.legendshow) {
        chart.legend(this.position.x, {
          position: this.legendposition,
          layout: this.legendlayout,
          itemFormatter: val => {
            return (
              val.toString() +
              (this.legendshowpercent
                ? ' (' +
                (dv.rows.find(ele => ele[this.position.x] === val) ? 
                  Math.round(
                    dv.rows.find(ele => ele[this.position.x] === val).percent *
                      10000,
                  ) /
                    100 : '') +
                  '%)'
                : '')
            );
          },
        });
        chart.legend(this.position.z, {
          position: this.legendposition,
          layout: this.legendlayout,
          itemFormatter: val => {
            return (
              val.toString() +
              (this.legendshowpercent
                ? ' (' +
                (dv.rows.find(ele => ele[this.position.z] === val)?
                  Math.round(
                    dv.rows.find(ele => ele[this.position.z] === val).percent *
                      10000,
                  ) /
                    100: '' )+
                  '%)'
                : '')
            );
          },
        });
      } else {
        chart.legend(false);
      }

    if (!this.innerpie)
      this.innerpie = chart
        .intervalStack()
        .position(`${this.position.y}`)
        .color(`${this.position.x}`)
        .label(`${this.position.x}`, {
          offset: -10
        })
        .select(false)
        .style({
          lineWidth: 1,
          stroke: '#fff',
        })
        .tooltip(
          `${this.position.x}*${this.position.y}*percent`,
          (x, y, percent) => {
            percent = (percent * 100).toFixed(2) + '%';
            return {
              name: x,
              value: y,
              percent,
            };
          },
        );

    const outterView = chart.view();
    const dv1 = new DataSet.View().source(tpdata);
    dv1.transform({
      type: 'sort-by',
      fields: [ this.position.x, this.position.z ], // 根据指定的字段集进行排序，与lodash的sortBy行为一致
      order: 'ASC'        // 默认为 ASC，DESC 则为逆序
    })
    dv1.transform({
      type: 'percent',
      field: this.position.y,
      dimension: this.position.z,
      as: 'percent',
    });
    outterView.source(dv1, {
      percent: {
        formatter: val => {
          val = (val * 100).toFixed(2) + '%';
          return val;
        },
      },
    });
    outterView.coord('theta', {
      innerRadius: 0.5 / 0.75,
      radius: 0.75,
    });
    if (!this.outterpie)
      this.outterpie = outterView
        .intervalStack()
        .position(`${this.position.y}`)
        .color(`${this.position.z}`)
        .label(`${this.position.z}`)
        .tooltip(
          `${this.position.z}*${this.position.y}*percent`,
          (z, y, percent) => {
            percent = (percent * 100).toFixed(2) + '%';
            return {
              name: z,
              value: y,
              percent,
            };
          },
        )
        .select(false)
        .style({
          lineWidth: 1,
          stroke: '#fff',
        });
    return dv.rows;
  }

  install() {
    this.render();
  }

  render() {
    console.log('line-stack-pie rendered')
    console.log(this)
    console.log(this.height)
    const { node, padding } = this;
    const container = node.nativeElement as HTMLElement;

    const chart = (this.chart = new G2.Chart({
      container,
      forceFit: true, // 图表的宽度自适应开关
      height: this.getHeight(),
      padding,
    }));

    this.commonStyleHandle(chart, this.data);

    chart.render();
  }

  attachChart() {
    const { chart, padding, data, color } = this;
    if (!chart || !data || data.length <= 0) return;
    const height = this.getHeight();
    if (chart.get('height') !== height) {
      chart.changeHeight(height);
    }
    const dvrows = this.commonStyleHandle(chart, this.data);
    // color
    //  chart.get('geoms')[0].color(this.colorFiled,this.color);
    chart.set('padding', padding);
    chart.changeData(dvrows);
  }

  destroy() {
    if (this.resize$) {
      this.resize$.unsubscribe();
    }
    if (this.chart) {
      this.ngZone.runOutsideAngular(() => this.chart.destroy());
    }
  }

  /**
   * 报表高度
   * 存在报表头，则需要减掉报表头的高度
   */
  getHeight() {
    return this.height;
    // return this.title ? (this.height - TITLE_HEIGHT) : this.height;
  }

  ngOnInit(): void {
    if (this.position && this.data.length > 0) {
      this.ngZone.runOutsideAngular(() =>
        setTimeout(() => this.render(), this.delay),
      );
    }
  }

  ngOnChanges(changes: import('@angular/core').SimpleChanges): void {
    this.ngZone.runOutsideAngular(() => this.attachChart());
  }
  ngOnDestroy(): void {
    this.destroy();
  }
}
